package handel

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"rikao19/cache"
	"rikao19/model"
	pkg2 "rikao19/pkg"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户为空",
		})
		return
	}
	redis_key := "redis_key" + username
	Datajson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if Datajson >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "错误三次",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Debug().Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg2.Md5str1(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if Datajson == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "封禁两个小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var data []model.User
	redis_list := "redis_list" + strconv.Itoa(page)
	Datajson, _ := cache.Rdb.Get(cache.Ctx, redis_list).Result()
	if Datajson == "" {
		model.DB.Offset(offset).Limit(size).Find(&data)
		Jsondata, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_list, Jsondata, time.Hour*2)

	} else {
		json.Unmarshal([]byte(Datajson), &data)
	}
	var total int64
	model.DB.Model(&model.User{}).Count(&total)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
	return

}
